// 浏览器本地数据库（IndexedDB）工具
// 用于跨页面共享“支行综合评分”等数据，避免重复取数

const DB_NAME = 'audit_view_db'
const DB_VERSION = 1
const STORE_NAME = 'kv'

export const KEY_BRANCH_SCORES = 'branch_scores_v1'

function openDB() {
  return new Promise((resolve, reject) => {
    try {
      const request = indexedDB.open(DB_NAME, DB_VERSION)

      request.onupgradeneeded = function (event) {
        const db = request.result
        if (!db.objectStoreNames.contains(STORE_NAME)) {
          db.createObjectStore(STORE_NAME, { keyPath: 'key' })
        }
      }

      request.onsuccess = function () {
        // console.debug('[scoreDB] open success', DB_NAME, DB_VERSION)
        resolve(request.result)
      }

      request.onerror = function () {
        console.warn('[scoreDB] open error:', request.error)
        reject(request.error)
      }
    } catch (err) {
      console.warn('[scoreDB] openDB exception:', err)
      reject(err)
    }
  })
}

async function withStore(mode, fn) {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const tx = db.transaction(STORE_NAME, mode)
    const store = tx.objectStore(STORE_NAME)
    const result = fn(store)
    tx.oncomplete = () => resolve(result)
    tx.onerror = () => reject(tx.error)
    tx.onabort = () => reject(tx.error)
  })
}

export async function setItem(key, value) {
  try {
    await withStore('readwrite', (store) => {
      store.put({ key, value, updatedAt: Date.now() })
    })
    // console.debug('[scoreDB] setItem ok:', key)
  } catch (e) {
    console.warn('[scoreDB] setItem failed, fallback to localStorage. key=', key, e)
    try {
      localStorage.setItem(key, JSON.stringify({ value, updatedAt: Date.now() }))
    } catch (lsErr) {
      console.error('[scoreDB] localStorage fallback failed:', lsErr)
    }
  }
}

export async function getItem(key) {
  try {
    const db = await openDB()
    return new Promise((resolve, reject) => {
      const tx = db.transaction(STORE_NAME, 'readonly')
      const store = tx.objectStore(STORE_NAME)
      const req = store.get(key)
      req.onsuccess = () => resolve(req.result ? req.result.value : null)
      req.onerror = () => reject(req.error)
    })
  } catch (e) {
    console.warn('[scoreDB] getItem failed, fallback to localStorage. key=', key, e)
    try {
      const raw = localStorage.getItem(key)
      if (!raw) return null
      const parsed = JSON.parse(raw)
      return parsed ? parsed.value : null
    } catch (lsErr) {
      console.error('[scoreDB] localStorage get fallback failed:', lsErr)
      return null
    }
  }
}

export async function removeItem(key) {
  await withStore('readwrite', (store) => store.delete(key))
}

export async function saveBranchScores(scoresMap) {
  // 保存评分映射
  await setItem(KEY_BRANCH_SCORES, scoresMap || {})
}

export async function loadBranchScores() {
  const data = await getItem(KEY_BRANCH_SCORES)
  return data || {}
}


